package com.kexin.jbsg.feiliu;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedList;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.kexin.jbsg.util.Util;

/**
 * @author oven:
 * @version 创建时间：2013-4-20 上午10:12:37
 * 
 */
public class PayActivityCard extends Activity {
	
	
	public static final String[] cardNames = {
											 "骏网一卡通",
											 "盛大游戏卡",
											 "移动充值卡",
											 "征途卡",
											 "Q币卡",
											 "联通卡",
											 "久游一卡通",
											 "易宝e卡通",
											 "网易一卡通",
											 "完美一卡通",
											 "搜狐一卡通",
											 "电信卡",
											 "纵游一卡通",
											 "天下通一卡通",
											 "天宏一卡通"
										};
	public final static int color_orange =  0xe47128;
	public final static int color_white = 0xe5e5e5;
	public Spinner spinner_card_type;
	public Spinner spinner_card_value;
	public TextView cardInfoHint;
	public EditText cardNo;
	public EditText cardPwd;
	public Button btn_backGame;
	public TextView welCome;
	
	public Button confirm;
	//
	public int cardType = 0;
	public int cardValue = 0;
	
	//用户信息
	public String userId;
	public String userRoleId;
	public String serverId;
	public String roleName;
	public String channel;
	
	public static LinkedList<CardTypeItem> cardTypes;
	public static LinkedList<LinkedList<CardValueItem>> cardValues;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pay_activity_card);
		
		userId = PayActivity.userId;
		userRoleId = PayActivity.userRoleId;
		serverId = PayActivity.serverId;
		roleName = PayActivity.roleName;
		channel = PayActivity.channel;
		
		welCome = (TextView) findViewById(R.id.recharge_userRole);
		welCome.setText(welCome.getText()+roleName);
		
		cardInfoHint = (TextView) findViewById(R.id.recharge_hint);
		
		//获取卡类型spinner
		spinner_card_type = (Spinner) findViewById(R.id.spinner_recharge_cards);
		//面值spinner
		spinner_card_value = (Spinner) findViewById(R.id.spinner_recharge_cards_vlue);
		
		//自定义adapter
		ArrayAdapter<CardTypeItem> adapter = new ArrayAdapter<CardTypeItem>(this, android.R.layout.simple_spinner_item, getCardTypeList()) {
            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = getLayoutInflater().inflate(R.layout.kom_spinner, parent, false);
                //文本
                TextView label = (TextView) view.findViewById(R.id.kom_spinner_label);
                label.setText(getItem(position).getTypeName());
                //图标
                if (spinner_card_type.getSelectedItemPosition() == position) {
                    //label.setTextColor(getResources().getColor(R.color.selected_fg));
                   // view.setBackgroundColor(color_white);
                    view.findViewById(R.id.kom_spinner_icon).setVisibility(View.VISIBLE);
                }
                return view;
            }
        };
        spinner_card_type.setAdapter(adapter);
        spinner_card_type.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				//卡类型
				CardTypeItem items = (CardTypeItem) arg0.getItemAtPosition(position);
				cardType = position;
				cardInfoHint.setText("温馨提示:\n  "+items.getHint());
				changeCardSpinnerValues(cardType);
				Log.i("infos", ""+position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
        	
		});
        
        
	    spinner_card_value.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				cardValue = arg2;
				Log.i("infos", ""+arg2);
			}
	
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
	      	
		});
	    
	    
	    cardNo = (EditText) findViewById(R.id.kom_card_no);
	    cardPwd = (EditText) findViewById(R.id.kom_card_pwd);
	    confirm = (Button) findViewById(R.id.recharge_confirm);
	    
	    confirm.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(v.getId()==R.id.recharge_confirm){
					boolean checkResult = true;
					//校验帐号密码是否为空
					String ScardNo = cardNo.getText().toString().trim();
					String ScardPwd = cardPwd.getText().toString().trim();
					if(ScardNo.equals("")){
						checkResult = false;
						cardNo.setError("卡号不能为空");
					}
					if(ScardPwd.equals("")){
						checkResult = false;
						cardPwd.setError("密码不能为空");
					}
					int cardType = spinner_card_type.getSelectedItemPosition();
					int cardValue = ((CardValueItem)spinner_card_value.getSelectedItem()).getValue();
					String toastString =  "cardType::"+ScardPwd+"  cardPwd"+ScardPwd+"  cardType::"+cardType+"   cardValue::"+cardValue;
					//Toast.makeText(TabActivity1.this,toastString, Toast.LENGTH_SHORT).show();
					if(checkResult){
						StringBuffer paramsb = new StringBuffer();
						//OrderType
						paramsb.append("OrderType="+cardType);
						//Denomination
						paramsb.append("&Denomination="+cardValue);
						//CardNO
						paramsb.append("&CardNO="+ScardNo);
						//CardPwd
						paramsb.append("&CardPwd="+ScardPwd);
						//serverId
						paramsb.append("&serverId="+serverId);
						//userId
						paramsb.append("&userId="+userId);
						//userRoleId
						paramsb.append("&userRoleId="+userRoleId);
						//channel
						paramsb.append("&channel="+channel);
						
						String sign = getMD5Str(userId+","+userRoleId+","+serverId+","+PayActivity.key);
						paramsb.append("&sign="+sign);
						
						payCard(paramsb.toString());
					}
				}
			}
		});
	    
	    
	    btn_backGame = (Button) findViewById(R.id.recharge_backGame);
	    btn_backGame.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				PayActivityCard.this.finish();
			}
		});
	}
	
	
	
	public void payCard(final String params){
		final Handler hd = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				boolean result = msg.getData().getBoolean("result");
				if(result){
					//Toast.makeText(PayActivityCard.this, "创建订单订单成功",Toast.LENGTH_SHORT).show();
					new AlertDialog.Builder(PayActivityCard.this)
	    			.setTitle("提示")
	    			.setMessage("订单提交成功!\n如长时间未到帐请尝试再次输入卡密进行充值!")
	    			.setPositiveButton("确定",null)
	    			.setNegativeButton("取消",null)
	    			.show();
				}else{
					Toast.makeText(PayActivityCard.this, "创建订单失败",Toast.LENGTH_SHORT).show();
				}
			}
		};
		
		new Thread(){
			public void run() {
				String result  = null;
				Message msg = new Message();
				Bundle data = new Bundle();
				try {
					result = Util.getWebCon(PayActivity.createOrderUrl+params);	
					if(result.equals("success")){
						data.putBoolean("result", true);
						msg.setData(data);
						hd.sendMessage(msg);
					}else{
						data.putBoolean("result", false);
						hd.sendMessage(msg);
					}
				} catch (Exception e) {
					data.putBoolean("result", false);
					hd.sendMessage(msg);
				}
			};
		}.start();
	}
	
	
	/**
	 * 更改面额数值
	 * @param cardType
	 */
	public void changeCardSpinnerValues(int cardType){
		ArrayAdapter<CardValueItem> adapter_value = new ArrayAdapter<CardValueItem>(this, android.R.layout.simple_spinner_item, getCardValueList().get(cardType)) {
            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = getLayoutInflater().inflate(R.layout.kom_spinner, parent, false);
                //文本
                TextView label = (TextView) view.findViewById(R.id.kom_spinner_label);
                CardValueItem item = getItem(position);
                label.setText(item.getValueString());
                //图标
                if (spinner_card_value.getSelectedItemPosition() == position) {
                    //label.setTextColor(getResources().getColor(R.color.selected_fg));
                   // view.setBackgroundColor(color_white);
                    view.findViewById(R.id.kom_spinner_icon).setVisibility(View.VISIBLE);
                }
                return view;
            }
        };
        spinner_card_value.setAdapter(adapter_value);
	}
	
	public static LinkedList<LinkedList<CardValueItem>> getCardValueList(){
		if(cardValues==null){
			cardValues = new LinkedList<LinkedList<CardValueItem>>();
			int[] junwang = {10,20,30,50,100,200,300,500};
			int[] shengda = {5,10,30,35,45,100,350,1000};
			int[] yidong = {10,20,30,50,100,200,300,500};
			int[] zhengtu = {5,10,15,18,20,25,30,50,60,68,100,120,180,208,250,300,468,500};
			int[] qq = {5,10,15,20,30,60,100,200};
			int[] liantong = {20,30,50,100,300,500};
			int[] jiuyou = {5,10,30,50};
			int[] yibao = {2,5,10,15,20,25,30,50,100};
			int[] wangyi = {10,15,20,30,50,};
			int[] wanmei = {15,30,50,100};
			int[] souhu = {5,10,15,30,40,100};
			int[] dianxin = {50,100};
			int[] zhongyou = {5,10,15,30,50,100};
			int[] tianxia = {5,6,10,15,30,50,100};
			int[] tianhong = {5,10,15,20,30,50,100};
			
			int[][] total = {junwang,shengda,yidong,zhengtu,qq,liantong,jiuyou,
					yibao,wangyi,wanmei,souhu,dianxin,zhongyou,tianxia,tianhong};
			
			for(int i=0;i<total.length;i++){
				int[] values = total[i];
				LinkedList<CardValueItem> child = new LinkedList<CardValueItem>();
				for(int j=0;j<values.length;j++){
					CardValueItem item = new CardValueItem();
					item.setValue(values[j]);
					child.add(item);
				}
				cardValues.add(child);
			}
		}
		return cardValues;
	}
	
	
	public static LinkedList<CardTypeItem> getCardTypeList(){
		if(cardTypes==null){
			cardTypes = new LinkedList<CardTypeItem>();
			String junwang = "※卡号、密码都是16位的阿拉伯数字";
			String shengda = "※卡号15位的数字字母，密码8位或9位的阿拉伯数字\n请使用卡号以CSC5、CS、S、CA、CSB、YC、YD开头的“盛大互动娱乐卡”进行支付";
			
			String yidong = "※全国卡：卡号17位、密码18位的阿拉伯数字\n" +
							"※地方卡：\n" +
									"浙江：卡号10位 密码8位\n"+
									"福建：卡号16位 密码17位\n"+
									"广东：卡号17位 密码18位\n"+
									"辽宁：卡号16位 密码21位\n"+
							"请务必使用与此面额相同的移动充值卡，否则会导致支付不成功，或支付金额丢失。 （使用面额100元的移动充值卡但选择50元，高于50元部分不返还；使用50元卡但选择100元，支付失败，50元不返还。） 不支持彩铃充值卡和短信充值卡，选择任何面额彩铃充值卡，将不予退还任何金额。";
			String zhengtu = "全国官方征途游戏充值卡，卡号16位阿拉伯数字，密码8位阿拉伯数字。\n" +
							 "※请务必使用与您所选择的面额相同的征途卡进行支付,否则引起的交易失败或交易金额丢失，我方不予承担！";
			String qq = "※全国各地Q币卡，卡号：9位的阿拉伯数字、密码：12位的阿拉伯数字。\n"+
						"※请务必使用与您所选面额相同的Q币卡进行支付，否则您将承担因此而引起的交易失败或者交易金额丢失所造成的损失。\n"+
						"※注意：只支持Q币卡卡密支付，不支持QQ账户内Q币或Q点支付";
			String liantong = "※联通全国卡，卡号15位阿拉伯数字，密码19位阿拉伯数字。\n"+
							  "※请务必使用与您选择的面额相同的联通充值卡进行支付，否则引起的交易失败交易金额不予退还。";
			
			String jiuyou = "※卡号13位、密码10位的阿拉伯数字\n"+
							"※请务必使用与您所选择的面额相同的久游一卡通进行支付,否则引起的交易失败或交易金额丢失，我方不予承担！";
			String yibao = "※卡号12或17位，卡密10位或18位阿拉伯数字";
			String wangyi = "※全国官方网易游戏充值卡，卡号13位、密码9位的阿拉伯数字\n"+
							"※请务必使用与您所选择的面额相同的网易一卡通进行支付,否则引起的交易失败或交易金额丢失，我方不予承担！";
			String wanmei = "※全国官方完美游戏充值卡，卡号10位、密码15位的阿拉伯数字\n"+
							"※ 9038、9037、8019号段暂时不支持\n"+
							"※请务必使用与您所选择的面额相同的完美一卡通进行支付,否则引起的交易失败或交易金额丢失，我方不予承担！";
			String souhu = "※卡号20位、密码12位的阿拉伯数字\n"+
						   "※请务必使用与您所选择的面额相同的搜狐一卡通进行支付,否则引起的交易失败或交易金额丢失，我方不予承担！";
			
			String dianxin = "※中国电信充值付费卡卡号19位，密码18位的阿拉伯数字（即：可拨打11888充值话费的卡）。\n"+
							 "※目前只支持电信全国卡和广东卡，充值卡序列号第四位为“1”的卡为全国卡，为“2”的则为广东卡。\n"+
							 "※请务必使用与您所选择的面额相同的电信卡进行支付,否则引起的交易失败或交易金额丢失，我方不予承担！";
			String zhongyou = "※卡号与密码均为15位阿拉伯数字。全国各地能买到纵游一卡通的地区，包括士多店、报刊亭、软件店、网吧、书店等。";
			String tianxia = "※卡号是15位阿拉伯数字，密码是8位阿拉伯数字，所有实卡的自发行日起，两年内有效。";
			String tianhong = "※卡号为12位，前2位是大写或小写英文字母，后10位是数字；密码15位是纯数字。\n"+
							  "※卡号为10位，前2位是大写或小写英文字母，后8位是数字；密码10位是纯数字。";
			
			String[] total = {junwang,shengda,yidong,zhengtu,qq,liantong,jiuyou,
					yibao,wangyi,wanmei,souhu,dianxin,zhongyou,tianxia,tianhong};
			
			for(int i=0;i<cardNames.length;i++){
				CardTypeItem item  = new CardTypeItem();
				item.setHint(total[i]);
				item.setTypeName(cardNames[i]);
				cardTypes.add(item);
			}
		}
		return cardTypes;
	}
	
	
	/** 
     * MD5 加密 
     */  
    public static String getMD5Str(String str) {  
        MessageDigest messageDigest = null;  
        try {  
            messageDigest = MessageDigest.getInstance("MD5");  
  
            messageDigest.reset();  
  
            messageDigest.update(str.getBytes("UTF-8"));  
        } catch (NoSuchAlgorithmException e) {  
            System.out.println("NoSuchAlgorithmException caught!");  
            System.exit(-1);  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
  
        byte[] byteArray = messageDigest.digest();  
  
        StringBuffer md5StrBuff = new StringBuffer();  
  
        for (int i = 0; i < byteArray.length; i++) {              
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)  
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));  
            else  
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));  
        }  
  
        return md5StrBuff.toString();  
    }  
	
}

